package cn.tedu.v1_1;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 聊天室version  1
 * 功能：1.客户端--指定IP，端口号
 * 2.客户端给服务器发送文本
 * 3.客户端完成标准IO
 * 【新增功能】4.捕获异常，打印异常信息--异常全部抓住，用户明确提示
 * 5.关闭socket
 * 192.168.166.8
 * 192.168.184.17
 */
public class Client {
    private Socket socket;
    public Client() {
        try {
            socket = new Socket("192.168.166.8", 1234);
        } catch (UnknownHostException e) {
            //用户地址出现问题异常
            System.out.println("IP地址有问题，请询问服务器端！");
        } catch (IOException e) {//IO异常：连接失败，客户端主动退出
            System.out.println("客户端主动退出了：断开连接");
        }
    }
    public void start()  {
        PrintWriter pw = null;    //置空流--赋值--关流
        try {
            OutputStream os = null;
            // InputStream is = null;
            OutputStreamWriter osw = null;
            //InputStreamReader  isr=null;
            BufferedWriter bw = null;
            //BufferedReader br=null;
            //PrintWriter pw = null;

            os = socket.getOutputStream();
            // is = socket.getInputStream();

            osw = new OutputStreamWriter(os, "UTF8");
            //isr=new InputStreamReader(is);

            bw = new BufferedWriter(osw);
            // br=new BufferedReader(isr);

            pw = new PrintWriter(bw, true);

            System.out.println("客户端用户请输入你的文字内容：");
            Scanner input = new Scanner(System.in);
            while (true) {
                String say = input.nextLine();
                pw.println(say);
                System.out.println("写出完毕");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端与服务器端：字符集不一致");
        } catch (IOException e) {
            System.out.println("客户端断开连接！");
        } finally {
            //关闭流  关闭socket
            if (pw != null)
                pw.close();
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端彻底断开连接");
            }
        }
    }
    public static void main(String[] args)  {
        Client client = new Client();
        client.start();
    }
}
